import 'dart:developer';

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:sports_new/resources/colours.dart';
import 'package:sports_new/resources/styles.dart';
import 'package:sports_new/utils/routes.dart';
import 'package:sports_new/utils/user.dart';
import 'package:sports_new/utils/utils.dart';
import 'package:sports_new/widgets/share/share_sheet.dart';
import 'package:webview_flutter/webview_flutter.dart';

import '../../widgets/base/qkd_text.dart';

class WebPara {
  WebPara(
    this.url,
    {
      this.title,
      this.longpress = false,
      this.header,
      this.shareButton,
      this.shareUrl
    }
  );
  String? title;
  final String url;
  final bool longpress;
  bool? shareButton;
  String? shareUrl;
  final Map<String,String>? header;
}

class MyWebPage extends StatefulWidget {
  const MyWebPage({super.key});

  @override
  State<MyWebPage> createState() => _MyWebPageState();
}

class _MyWebPageState extends State<MyWebPage> {
  late WebPara para;
  late WebViewController wcontroller;
  late final webview = WebViewWidget(controller: wcontroller);

  @override
  void initState() {
    if (Get.arguments is WebPara) {
      para = Get.arguments as WebPara;
    } else if (Get.arguments is Map<String, dynamic>) {
      final map = Get.arguments as Map<String, dynamic>;
      log("map = $map");
      para = WebPara("${map["url"]}",
        title: "${map["title"] ?? ""}",
        longpress: map['longpress'] ?? false);
    }else{
      para = WebPara("");
    }
    if(Get.parameters.isNotEmpty){
      var params = Get.parameters;
      para.shareButton = params['shareButton'] == "1";
      if(para.title.noValue) para.title = params['title'];
      para.shareUrl = params['shareUrl'];
    }
    wcontroller = WebViewController()
      ..setJavaScriptMode(JavaScriptMode.unrestricted)
      ..setNavigationDelegate(NavigationDelegate(
        onNavigationRequest: (request) async => NavigationDecision.navigate,
      ))
      ..addJavaScriptChannel("WEB_QXB", onMessageReceived: (msg) {
        Utils.doJump(msg.message);
        if(msg.message.contains(Routes.share)){
          Utils.onEvent("coin_invitation_now");
        }else if(msg.message.contains(Routes.myCoupons)){
          Utils.onEvent("new_activity_view");
        }
      })
      ..setBackgroundColor(Colours.scaffoldBg)
      ..loadRequest(Uri.parse(para.url.replaceFirst("UserId", "${User.info?.id}").replaceFirst("Token", "${User.auth?.token}")));
    super.initState();
  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colours.scaffoldBg,
      appBar: Styles.appBar(
        title: QkdText(para.title??""),
        actions: [
          if(para.shareUrl.hasValue && (para.shareButton??false))
          GestureDetector(
            onTap: ()=> Routes.toPage(
                Routes.share,
                arguments: ShareEntity(
                  url: para.shareUrl??"",
                )
              ),
            child: Container(
              height: Get.height,
              margin: const EdgeInsets.only(right: 16),
              child: Image.asset(
                Utils.getImgPath("icon_share.png"),
                width: 24,height: 24,
              ),
            ),
          )
        ],
        onTapLeading: () async {
          final goback = !(await wcontroller.canGoBack());
          if (!goback) {
            wcontroller.goBack();
          } else {
            Get.back();
          }
        },
      ),
      body: para.longpress
        ? GestureDetector(
          onLongPress: () {},
          behavior: HitTestBehavior.opaque,
          child: webview
      ) : webview,
    );
  }
}
